// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

mod command;
mod plugins;
mod tray;

use command::{
    tokios::{server_init_complete, PageInitState},
    KoiTauriCommand,
};
use plugins::KoiTauriPlugin;
use std::sync::Mutex;
use tauri::async_runtime::spawn;

use tauri_plugin_global_shortcut::{Code, GlobalShortcutExt, Modifiers, Shortcut, ShortcutState};

fn main() {
    tauri::Builder::default()
        .plugin(tauri_plugin_updater::Builder::new().build())
        .init_plugin()
        .manage(Mutex::new(PageInitState {
            frontend: false,
            backend: false,
            isloaded: false,
        }))
        .setup(|app| {
            #[cfg(all(desktop))]
            {
                let all_l_shortcut: Shortcut = Shortcut::new(Some(Modifiers::ALT), Code::KeyL);
                app.handle().plugin(
                    tauri_plugin_global_shortcut::Builder::new()
                        .with_handler(move |_app, shortcut, event| {
                            println!("{:?}", shortcut);
                            if shortcut == &all_l_shortcut {
                                match event.state() {
                                    ShortcutState::Pressed => {
                                        println!("All-L 我是快捷键，我来了..!");
                                    }
                                    ShortcutState::Released => {
                                        println!("All-L 我是快捷键，我走了..");
                                    }
                                }
                            }
                        })
                        .build(),
                )?;
                app.global_shortcut().register(all_l_shortcut)?;

                tray::create_tray(app.handle())?;
            }

            spawn(server_init_complete(app.handle().clone())); // 服务器初始化完成
            Ok(())
        })
        .init_cmd()
        .run(tauri::generate_context!())
        .expect("启动应用程序出错..");
}
